<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>

		<view v-show="currentRW ">
			<scroll-view
			  scroll-y="true"
			  :style="{ height: computedScrollViewHeight }"
			  
			>
			<!-- style="margin: 20px 0" -->
				<view class="margin-sm">
					<u-form class="form" ref="uForm" label-position="left" :model="model" :rules="rules">
						<u-form-item label="机台" prop="lineCode" label-width="180" :required="true">
							<view class="flex"><u-input placeholder="请扫码" v-model="model.lineCode" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
								  <text class="cuIcon-roundclose" @tap="clearOperator('lineCode')" v-if="model.lineCode"></text>
							</view>
						</u-form-item>
						<u-form-item label="操作工" prop="operators" label-width="180" :required="true">
							<view class="flex"><u-input placeholder="请扫码" v-model="model.operators" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
								  <text class="cuIcon-roundclose" @tap="clearOperator('operators')" v-if="model.operators"></text>
								  
							</view>
						</u-form-item>
						<u-form-item label="工序" prop="operCode" label-width="180" :required="true">
							<view class="flex">
								<u-input placeholder="请扫码" v-model="model.operCode" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
								<text class="cuIcon-roundclose" @tap="clearOperator('operCode')" v-if="model.operCode"></text>
							</view>
						</u-form-item>
					</u-form>
					
				</view>
				
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group">
				<!-- round -->
				<button class="cu-btn bg-confirm lg margin-left " @click="confirm">派工</button>	
			</view>
		</view>
		
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>
		<custom-modal ref="customModal" v-if="showModal" :initial-message="modalMessage" @update:close="onModalClose" ></custom-modal>
	</view>
</template>

<script>
	import CustomModal from "@/pages/mes/components/CustomModal.vue";
	import dictLabel from "@/pages/mes/components/dictLabel.vue";
	export default {
		components: {
			CustomModal,
			dictLabel
		},
		data() {
			return {
				focus:true,
				focusGP:false,
				barCode:'',
				barCodeGP : '',
				model: { },
				rules: {
					operator: [
						{
							required: true,
							message: '请扫码操作工',
							trigger: ['change','blur'],
						}
					]
				},
				customStyle:{
					color:'red'
				},
				showModal: false,
				scrollViewHeight: 0,
				currentRW:true,
				emptyViewHeight:0,
				list:[],
				modid:'',
				lineCode:'',
				dictList:[],
				operatorNames:{},
				showFlag:false,
			}
		},
		onShow() {
			// 在onShow中监听事件
			uni.$once('selectedItems', (selectedItems) => {
				// 去重
				const uniqueSelectedItems = Array.from(new Set(selectedItems.map(item => item.id)));
				// 从this.list中过滤出不在uniqueSelectedItems中的项
				const filteredList = this.list.filter(item => !uniqueSelectedItems.includes(item.id));
				// 合并并去重
				this.list = [...filteredList, ...selectedItems].filter(
					(item, index, self) => self.findIndex(i => i.id === item.id) === index
				);
				// 遍历加一个显示操作工的标识
				// this.list.forEach(item => {
				// 	item.showOperation = true;
				// });
				this.focus = false;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 500);
				console.log(this.list, 'merged and deduplicated list');
			});
			this.getDictList()
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		onUnload(){
			uni.$off('selectedItems');
		},
		methods:{
			clearOperator(item){
				if(item == 'operators'){
					this.showCustomModal("确定要删除操作工").then((res) => {
						if(res){
							this.model.operators = ''
							this.operatorNames = {}
							this.$forceUpdate()
						}
					})
				}else if(item == 'lineCode'){
					this.showCustomModal("确定要删除产线").then((res) => {
						if(res){
							this.model.lineCode = ''
							this.$forceUpdate()
						}
					})
				}else if(item == 'operCode'){
					this.showCustomModal("确定要删除工序").then((res) => {
						if(res){
							this.model.operCode = ''
							this.$forceUpdate()
						}
					})
				}
				
			},
			getDictList() {
				this.$u.api
					.dictListData({ dictType: "mes_task_status" })
					.then((res) => {
					this.dictList = res;
				});		
			},
			DelItem(item) {
				this.showCustomModal("确定删除吗？").then((res) => {
					if(res){
						const index = this.list.findIndex((element) => element.id === item.id); // 假设每个item有一个唯一的id属性
						if (index !== -1) {
							// 从数组中移除找到的项
							this.list.splice(index, 1);
						}
					}
				})
			},
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
			      console.log(this.$refs,'this.$refs')
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0 ;
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 80 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
				  // 等待头部高度计算完成
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){	
				this.focus = false
				this.commonSearch(this.barCode)			
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				if(barCode.indexOf(JT) == 0){
					const res = await this.$u.api.kst.checkFunAndBar({
						funcType: this.vuex_config.JT,
						barJT: barCode
					});
					if (res.result == "true") {
						if(res.errorMsg){
							setTimeout(() => {
								this.focus = true;
							}, 500);
							this.$refs.jsError.showError('',res.message,'error');
							return;
						}
						await this.$nextTick();
						this.barCode = '';
						this.model.lineCode = res.basLine.code;
						setTimeout(() => {
							this.barCode = '';
							this.focusGP = true;
						}, 500);
						this.$forceUpdate()	
						
					} else {
						this.$u.toast(res.message);
						setTimeout(() => {
							this.focus = true;
						}, 500);
					}
				} else if(barCode.indexOf(GP) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){

						let operatorName = res.operator.name;

						let operatorCode = res.operator.code;
						
						let bmonitor = res.operator.bmonitor;

						// 累加操作员名称或设置初始值
						if (this.operatorNames[barCode]) {
							operatorName = `${this.operatorNames[barCode]},${operatorName}`;
						}
						this.operatorNames[barCode] = operatorName;
						// this.operatorNames 去重
						this.operatorNames = [...new Set(Object.values(this.operatorNames))]
						
						const operatorNamesStr = Object.values(this.operatorNames).join(',');
						await this.$nextTick();
						this.barCode = '';
						this.model.operators = operatorNamesStr
						setTimeout(() => {
							this.barCode = '';
							this.focusGP = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				}else{
					this.model.operCode = barCode
					setTimeout(() => {
						this.barCode = '';
						this.focusGP = true;
					}, 500);
					this.$forceUpdate()	
				}
			},
			// 扫工牌开始
			confirmSearchGP(){	
				this.focusGP = false
				this.commonSearchGP(this.barCodeGP)			
			},
			searchGP(){
				var _that = this;
				_that.focusGP = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearchGP(res.result)
					},
				});
			},
			async commonSearchGP(barCode){				
				let GP = this.vuex_config.GP;
				if (barCode.indexOf(GP) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的工牌",'error');
					setTimeout(() => {
						this.barCodeGP = ''
						this.focusGP = true;
					}, 500);
					return;
				} else if(barCode.indexOf(GP) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){
						let operatorName = res.operator.name;
						let bmonitor = res.operator.bmonitor;
						// 累加操作员名称或设置初始值
						// if (this.operatorNames[barCode]) {
						// 	operatorName = `${this.operatorNames[barCode]},${operatorName}`;
						// }
						// this.operatorNames[barCode] = operatorName;
						// // this.operatorNames 去重
						// this.operatorNames = [...new Set(Object.values(this.operatorNames))]
						// const operatorNamesStr = Object.values(this.operatorNames).join(',');
						await this.$nextTick();
						this.barCode = '';
						if(bmonitor == '1'){
							this.list.forEach((item) => {
								item.monitor = operatorName
							})
							this.barCodeGP = operatorName
							setTimeout(() => {
								this.barCode = '';
								this.focus = true;
							}, 500);
						}else{
							this.$refs.jsError.showError('', '请扫码班长工牌', 'error');	
							setTimeout(() => {
								this.barCodeGP = '';
								this.focusGP = true;
							}, 500);
						}	
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				}
			},			
			// 扫工牌结束
			confirm(){
				// 获取list的id,字符串逗号分隔
				if(!this.model.lineCode){
					this.$refs.jsError.showError('', '请扫码机台', 'error');
					return;
				}
				if(!this.model.operators){
					this.$refs.jsError.showError('', '请扫码操作工', 'error');
					return;
				}
				if(!this.model.operCode){
					this.$refs.jsError.showError('', '请扫码工序', 'error');
					return;
				}
				
				this.$u.api.kst.autoPg(this.model).then(async (res)=>{
					if(res.result=="true"){
						this.$u.toast(res.message);
						this.model = {}
						this.operatorNames = {}
						// this.list[0].operator = '';
						// const resResult = await this.$u.api.kst.getTaskByLineCode({ lineCode: this.lineCode });
						// if (resResult.result == "true") {
						// 	this.list = resResult.data;
						// 	this.list.forEach((item) => {
						// 		item.isDelFlag = false;
						// 	});
						// 	this.showFlag = this.list.length > 0 ? true : false;
						// }
						this.$forceUpdate()
					}else{
						// this.$u.toast(res.message);
						this.$refs.jsError.showError('',res.message,'error');
					}
				})

			},
			selectSJ(){
				uni.navigateTo({
					url: "/pages/mes/shangji/bSelect?modid=" + this.modid + '&lineCode=' + this.lineCode
				});
			},
			async showCustomModal(message) {
			  this.modalMessage = message;
			  this.showModal = true;
			  // 模拟同步等待用户操作
			  return new Promise((resolve) => {
			    this.onModalClose = (result) => {
			      this.modalResult = result;
			      this.showModal = false;
			      resolve(this.modalResult);
			    };
			  });
			},
			onModalClose(result) {
			  this.$emit("update:close", result);
			},
			onErrorClose(result) {
			//   this.$emit("update:errorcClose", result);
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			 
			},
		}
	}	
</script>

<style scoped>

	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.title{
		width: 180rpx;
	}
	.text-sl{
		font-size: 60rpx;
	}
	.dictLabel{
		position: absolute;
		top: -10px;
		right: -10px;
	}
</style>